package com.tanhua.sso.service;


import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.tanhua.sso.config.AliyunSMSConfig;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
@Slf4j
public class SmsService {

    @Autowired
    private AliyunSMSConfig aliyunSMSConfig;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 利用阿里云短信服务发送验证码  成功返回验证码
     * @param mobile
     * @return
     */
    public String sendSms(String mobile){

        DefaultProfile profile = DefaultProfile.getProfile(this.aliyunSMSConfig.getRegionId(),
                this.aliyunSMSConfig.getAccessKeyId(), this.aliyunSMSConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        //生成6位随机验证码
        String code = RandomUtils.nextInt(100000, 999999) + "";

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");

        request.putQueryParameter("RegionId", this.aliyunSMSConfig.getRegionId());

        request.putQueryParameter("PhoneNumbers", mobile); //目标手机号

        request.putQueryParameter("SignName", this.aliyunSMSConfig.getSignName()); //签名名称

        request.putQueryParameter("TemplateCode", this.aliyunSMSConfig.getTemplateCode()); //短信模板code

        request.putQueryParameter("TemplateParam", "{\"code\":\""+code+"\"}");//模板中变量替换
        try {
            CommonResponse response = client.getCommonResponse(request);

            System.out.println(response.getData());
            //{"Message":"OK","RequestId":"EC2D4C9A-0EAC-4213-BE45-CE6176E1DF23","BizId":"110903802851113360^0","Code":"OK"}

            String data = response.getData();

            if (StringUtils.contains(data,"\"Message\":\"OK\"")){
                //成功返回验证码
                return code;
            }
            //记录日志 和 date
            log.info("验证码发送失败 date" + data);

        } catch (Exception e) {
            //记录异常信息

            log.error("验证码发送失败"+mobile,e);
        }
        //失败返回空
        return null;

    }

    /**
     *  发送验证码 并将验证码保存到redis中
     * @param phone
     * @return
     */
    public ErrorResult sendCheckCode(String phone){

        String redisKey ="CHECK_CODE_"+phone;
        String msg=null;

        //先判断该手机号发送的验证码是否还未失效
        if (this.redisTemplate.hasKey(redisKey)) {
            msg="验证码还未失效..";
            return ErrorResult.builder().errCode("填未失效验证码").errMessage(msg).build();
        }


        //如果未失效 再发送的验证码 然后判断是否发送成功
        // String code = sendSms(phone);

        //测试时写死验证码为123456
        String code = "123456";

        if (StringUtils.isEmpty(code)){
            msg ="验证码发送失败";
           return ErrorResult.builder().errCode("此处填错误码xxxx").errMessage(msg).build();
        }

        //如果发送成功 则把验证码存在redis中 并设置有效期为五分钟
        this.redisTemplate.opsForValue().set(redisKey,code);

        //如果成功则返回空
        return null;


    }
}
